package com.key.service.impl;

import com.key.common.R;
import com.key.common.dto.SysUserMenuDTO;
import com.key.common.vo.UserVO;
import com.key.common.vo.SysUserVo;
import com.key.entity.Employee;
import com.key.entity.SysMenu;
import com.key.entity.SysRole;
import com.key.entity.SysUser;
import com.key.mapper.EmployeeMapper;
import com.key.mapper.SysMenuMapper;
import com.key.mapper.SysUserMapper;
import com.key.service.SysUserService;
import com.key.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.config.annotation.CorsRegistry;

import javax.management.relation.Role;
import javax.servlet.http.HttpServletResponse;
import java.rmi.registry.Registry;
import java.util.*;

/*
 *
 * @author liu
 *
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public R login(UserVO userVO, HttpServletResponse response) {
        R r = new R();
        String userName = userVO.getUserName();
        String password = userVO.getPassword();
        try {
            SysUser sysUser = sysUserMapper.findSysUerByUserName(userName);
            if (sysUser == null){
                throw new UnknownAccountException();
            }
            if (sysUser.getUserState()==0){
                throw new DisabledAccountException();
            }
            //显示加密的密码
            SimpleHash simpleHash=new SimpleHash("md5",password,"gxa",2);
            System.out.println(simpleHash.toString());
            //4. 得到主体
            Subject subject = SecurityUtils.getSubject();
            //5. 获取相应的 token -- 客户端传递的参数
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName,password);
            //6. 登录
            subject.login(usernamePasswordToken);
            //7. 程序代码能走到这里，就表示登录成功！
            r.setCode(200);
            r.setMsg("登录成功");
            //查询用户具有权限
            Employee employee = employeeMapper.findEmployeeByUserId(sysUser.getUserId());
            List<SysMenu> sysMenus = sysMenuMapper.findSysMenuByUserId(sysUser.getUserId());
            //遍历去重
            Set<SysMenu> sysMenuss = new HashSet<>();
            for (SysMenu s:sysMenus) {
                sysMenuss.add(s);
            }
            sysMenus.clear();
            sysMenus.addAll(sysMenuss);
            SysUserMenuDTO sysUserMenuDTO=new SysUserMenuDTO(sysUser,employee,sysMenus);
            r.setData(sysUserMenuDTO);
            //生成token唯一标识符
            String token  = JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT,userName,JwtUtils.TTMILLIS);
            String refreshToken = JwtUtils.createJwt(UUID.randomUUID().toString(), JwtUtils.JWT_SECERT, userName, JwtUtils.RTTMILLIS);
            //颁发给客户端--返回给客户端，怎么返回？
            //通过响应头返回 response
            response.setHeader("Access-Control-Expose-Headers", "Authorization,RAuthorization");
            response.addHeader("Authorization",token);
            //response.setHeader("Access-Control-Expose-Headers", "RAuthorization");
            response.addHeader("RAuthorization",refreshToken);

        } catch (UnknownAccountException e){
            System.out.println("==账户有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (IncorrectCredentialsException e){
            System.out.println("==密码有误==");
            r.setCode(500);
            r.setMsg("账户或密码有误");
        }catch (DisabledAccountException e){
            System.out.println("==账号被禁用==");
            r.setCode(500);
            r.setMsg("账号被禁用");
        }catch (AuthenticationException e){
            System.out.println("==认证错误==");
            r.setCode(500);
            r.setMsg("认证错误");
        }
        return r;
    }





    /**
     * 显示用户
     * @return
     */
    @Override
    public List<SysUserVo> findSysUser() {
        List<SysUserVo> sysUserVos = sysUserMapper.findSysUser();
        return sysUserVos;
    }

    /**
     * 增加用户
     * @param sysUsers
     * @return
     */
    @Override
    public boolean addSysUser(SysUser sysUsers) {
        //显示加密的密码
        String userPassword = sysUsers.getUserPassword();
        SimpleHash simpleHash=new SimpleHash("md5",userPassword,"gxa",2);
        System.out.println(simpleHash.toString());
        sysUsers.setUserPassword(userPassword);
        int s = sysUserMapper.addSysUser(sysUsers);
        if(s>0){
            int employeeId = sysUserMapper.findEmployeeIdByName(sysUsers.getUserContact());
            Map<String,Integer> map = new HashMap<>();
            int userId = sysUserMapper.findSysUserIdByUserName(sysUsers.getUserName());
            map.put("userId",userId);
            map.put("employeeId",employeeId);
            sysUserMapper.updateEmployeeById(map);
            return true;
        }else{
            return false;
        }
    }


    /**
     * 根据用户Id删除用户
     * @param sysUserId
     * @return
     */
    @Override
    public boolean deleteSysUser(Integer sysUserId) {
        int s = sysUserMapper.deleteSysUser(sysUserId);
        if(s>0){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 根据账户和姓名查找用户信息
     * @return
     */
    @Override
    public List<SysUser> findSysUserByAccountAndName(String string) {
        List<SysUser> sysUsers = sysUserMapper.selectUserByAccount(string);
        List<SysUser> sysUser = sysUserMapper.selectUserByName(string);
        if(sysUsers.size()>0){
            return sysUsers;
        }else{
            return sysUser;
        }
    }

    /**
     * 修改用户列表
     * @param sysUser
     * @return
     */
    @Override
    public boolean updateUser(SysUser sysUser) {
        int s = sysUserMapper.updateUser(sysUser);
        if(s>0){
            return true;
        }else{
            return false;
        }
    }


    /**
     *根据用户Id查询角色
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> findRoleByUserId(Integer userId) {
        List<SysRole> roles = sysUserMapper.findRoleByUserId(userId);
        return roles;
    }

    /**
     * 先增再删用户角色
     * @param userId
     * @param roleId
     * @return
     */
    @Override
    public boolean deleteAddUserRole(Integer userId, Integer[] roleId) {
//        int s = sysUserMapper.deleteUserRole(userId);
//        if(roleId == null || !" ".equals(roleId)){
//            String[] ids = roleId.split(",");
//            for(String id:ids){
//                Map<String,Integer> map = new HashMap<>();
//                map.put("userId",userId);
//                map.put("roleId",Integer.parseInt(id));
//                int a = sysUserMapper.addSysUserRole(map);
//                return true;
//            }
//            return false;
//        }
//        return false;
        int s = sysUserMapper.deleteUserRole(userId);
        for(int i=0;i<roleId.length-1;i++) {
            Map<String, Integer> map = new HashMap<>();
            map.put("userId",userId);
            map.put("roleId",roleId[i]);
            sysUserMapper.addSysUserRole(map);
            return  true;
        }

        return false;
    }

    /**
     * 查询未关联用户的员工
     * @return
     */
    @Override
    public List<Employee> findEmployeeByBreak() {
        List<Employee> employees = sysUserMapper.findEmployeeByBreak();
        return employees;
    }


}
